package com.epower.web.action.epoweruser;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import com.epower.base.BaseAction;
import com.epower.bo.epower.commons.Constants;
import com.epower.bo.epower.commons.Md5Utils;
import com.epower.bo.epoweruser.EpowerUserService;
import com.epower.dataobject.EpowerUserDO;

@Scope("prototype")
@Component()
public class EpowerUserAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	/*** 查询对象 ***/
	private EpowerUserDO query;

	/*** 对象集合 ***/
	private List<EpowerUserDO> epowerUserList;

	/*** BO ***/
	private EpowerUserService epowerUserBO;

	/*** 主键 ***/
	private Integer id;

	/*** 查询对象 ***/
	private EpowerUserDO epowerUser;

	/*** 当前action所在的namespace ***/
	private String namespace = "epoweruser";
	/*** 当前action对应的module ***/
	private String moduleName = "EpowerUser";

	private String errMsg;

	/***
	 * 编辑视图
	 * 
	 * @return
	 * @throws Exception
	 */
	public String viewEditEpowerUser() throws Exception {
		epowerUser = epowerUserBO.getEpowerUserById(id);
		return SUCCESS;
	}

	/***
	 * 编辑操作
	 * 
	 * @return
	 * @throws Exception
	 */

	public String editEpowerUser() throws Exception {
		epowerUser.setStatus(Constants.STATUS_OK);
		epowerUser.setType(Constants.USER_COMMON);
		if (!epowerUserBO.updateEpowerUserByOption(epowerUser)) {
			addActionMessage("编辑失败");
			return SUCCESS;
		}
		addActionMessage("编辑成功");
		return SUCCESS;
	}

	/***
	 * 添加视图
	 * 
	 * @return
	 * @throws Exception
	 */
	public String doViewRegisrer() throws Exception {
		return SUCCESS;
	}

	/***
	 * 添加操作
	 * 
	 * @return
	 * @throws Exception
	 */
	public String doRegister() throws Exception {

		if (!checkUser()) {
			return ERROR;
		}
		if (epowerUserBO.addEpowerUser(epowerUser) == null) {
			addActionMessage("添加失败");
			return SUCCESS;
		}
		saveUserSession(Constants.USER_NAME, epowerUser.getUsername());
		return SUCCESS;
	}

	/**
	 * 用户推出,清理掉cookie和session
	 * 
	 * @return
	 */
	public String doLogOut() {

		clearUser();
		return SUCCESS;

	}

	public boolean checkUser() {

		if (epowerUser == null || StringUtils.isBlank(epowerUser.getUsername()) || epowerUser.getUsername().length() < 6
				|| StringUtils.isBlank(epowerUser.getMail()) || epowerUser.getMail().indexOf("@") < 0) {
			errMsg = "名称为空,或者邮件格式不正确!";
			return false;
		}
		if (epowerUser.getUsername().indexOf("@") > -1) {
			errMsg = "名称中不能包含类似@的特殊字符!";
			return false;
		}
		if (epowerUserBO.getUserByUserName(epowerUser.getUsername()) != null) {
			errMsg = "该用户已经存在!";
			return false;
		}
		if (StringUtils.isBlank(epowerUser.getPassword())) {
			errMsg = "密码不能为空!";
			return false;
		}
		EpowerUserDO user = new EpowerUserDO();
		user.setMail(epowerUser.getMail());
		user.setStatus(Constants.STATUS_OK);
		if (epowerUserBO.getEpowerUserByOption(user) != null) {
			errMsg = "该邮箱已经被使用!";
			return false;
		}
		if (!epowerUser.getPassword().equals(epowerUser.getRepassword())) {
			errMsg = "两次输入的密码不一致!";
			return false;
		}
		epowerUser.setStatus(Constants.STATUS_OK);
		epowerUser.setType(Constants.USER_COMMON);
		epowerUser.setPassword(initPassWord(epowerUser.getPassword()));
		return true;
	}

	public String doViewLogin() {
		return SUCCESS;
	}

	private String rememberLogin;

	private boolean checkLoginUser() {
		if (epowerUser == null) {
			return false;
		}
		if (epowerUser.getUsername() == null) {
			errMsg = "用户不存在!";
			return false;
		}
		if (epowerUser.getPassword() == null) {
			errMsg = "密码不能为空!";
			return false;
		}
		return true;
	}

	public String doLogin() {

		if (!checkLoginUser()) {
			return ERROR;
		}

		// 输入的是邮箱
		if (epowerUser.getUsername().indexOf("@") > -1) {
			epowerUser.setMail(epowerUser.getUsername());
			epowerUser.setUsername(null);
		}
		epowerUser.setStatus(Constants.STATUS_OK);
		epowerUser.setType(Constants.USER_COMMON);
		epowerUser.setPassword(initPassWord(epowerUser.getPassword()));
		if ((epowerUser = epowerUserBO.getEpowerUserByOption(epowerUser)) == null) {
			errMsg = "用户不存在,或者密码错误!";
			return ERROR;
		} else {
			// 如果记住了登录,将记住登录的cookie写进来,默认保留一年
			if (rememberLogin != null) {
				saveUserCookie(Constants.USER_NAME, epowerUser.getUsername(), Constants.ONE_YEAR);
			}

			saveUserSession(Constants.USER_NAME, epowerUser.getUsername());
		}
		return SUCCESS;
	}

	private String username;
	private String mail;

	private void clearUser() {
		Cookie cookie = new Cookie(Constants.USER_NAME, null);
		HttpServletResponse response = ServletActionContext.getResponse();
		cookie.setPath("/");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
		ServletActionContext.getRequest().getSession().setAttribute(Constants.USER_NAME, null);
	}

	/**
	 * 查看是否存在该用户,isSuccess位true的时候表示不存在,false的时候表示存在
	 * 
	 * @throws JSONException
	 * @throws IOException
	 */
	public void checkUserName() throws JSONException, IOException {
		JSONObject result = new JSONObject();
		result.put("isSuccess", false);
		if (!StringUtils.isBlank(username)) {
			EpowerUserDO epower = new EpowerUserDO();
			epower.setStatus(Constants.STATUS_OK);
			epower.setType(Constants.USER_COMMON);
			epower.setUsername(username);
			epower = epowerUserBO.getEpowerUserByOption(epower);
			if (epower == null) {
				result.put("isSuccess", true);
			}
		}

		super.write(result.toString());
	}

	/**
	 * 查看是否存在该邮箱,isSuccess位true的时候表示不存在,false的时候表示存在
	 * 
	 * @throws IOException
	 * @throws JSONException
	 */
	public void checkUserMail() throws IOException, JSONException {
		JSONObject result = new JSONObject();
		result.put("isSuccess", false);
		if (!StringUtils.isBlank(mail)) {
			EpowerUserDO epower = new EpowerUserDO();
			epower.setStatus(Constants.STATUS_OK);
			epower.setType(Constants.USER_COMMON);
			epower.setMail(mail);
			epower = epowerUserBO.getEpowerUserByOption(epower);
			if (epower == null) {
				result.put("isSuccess", true);
			}
		}
		super.write(result.toString());

	}

	public void saveUserCookie(String key, String value, int expiry) {

		Cookie cookie = new Cookie(key, value);
		HttpServletResponse response = ServletActionContext.getResponse();
		cookie.setPath("/");
		if (expiry > 0)
			cookie.setMaxAge(expiry);
		response.addCookie(cookie);

	}

	public void saveUserSession(String key, Object value) {
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute(key, value);

	}

	public String initPassWord(String passWord) {

		return Md5Utils.md5(passWord + Constants.USER_MD5_KEY);

	}

	/*** setter getter start ***/
	public EpowerUserDO getQuery() {
		return query;
	}

	public void setQuery(EpowerUserDO query) {
		this.query = query;
	}

	public List<EpowerUserDO> getEpowerUserList() {
		return epowerUserList;
	}

	public void setEpowerUserList(List<EpowerUserDO> epowerUserList) {
		this.epowerUserList = epowerUserList;
	}

	public EpowerUserService getEpowerUserBO() {
		return epowerUserBO;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	@Resource
	public void setEpowerUserBO(EpowerUserService epowerUserBO) {
		this.epowerUserBO = epowerUserBO;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public EpowerUserDO getEpowerUser() {
		return epowerUser;
	}

	public void setEpowerUser(EpowerUserDO epowerUser) {
		this.epowerUser = epowerUser;
	}

	public String getNamespace() {
		return namespace;
	}

	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	public String getModuleName() {
		return moduleName;
	}

	public String getRememberLogin() {
		return rememberLogin;
	}

	public void setRememberLogin(String rememberLogin) {
		this.rememberLogin = rememberLogin;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	public String getErrMsg() {
		return errMsg;
	}

	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}

	/*** setter getter end ***/
}
